package ui.swing.table;

import java.awt.BorderLayout;
import java.awt.Component;
import java.io.Serializable;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;

public class Table_Renderer extends JFrame {

	private static final long serialVersionUID = -1630724713946274254L;

	public Table_Renderer() {
		super("你好");
		setBounds(200, 200, 500, 400);

		JTable tbl_grade = new JTable(new MyTable());
		JComboBox cmb_loc = new JComboBox(new String[] { "北京", "重庆", "上海" });
		/* 我们利用JTable所提供的getTableColumnModel()方法取得TableColumnModel对象,
		 * 再由TableColumnModel类所提供的getColumn()方法取得TableColumn对象,TableColumn类
		 * 可针对表格中的每一行做具体的设置,例如设置字段的宽度,某行的标头,设置输入较复杂的数据类型
		 * 等等.在这里,我们利用TableColumn类所提供的setCellEditor()方法,将JComboBox作为第二
		 * 行的默认编辑组件.
		 */
		tbl_grade.getColumnModel().getColumn(1).setCellEditor(
				new DefaultCellEditor(cmb_loc));
		tbl_grade.getColumnModel().getColumn(7).setCellRenderer(
				new MyCellRenderer());

		getContentPane().add(tbl_grade, BorderLayout.CENTER);
		getContentPane().add(tbl_grade.getTableHeader(), BorderLayout.NORTH);

		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);
	}

	class MyTable extends AbstractTableModel {

		private static final long serialVersionUID = -990368661444638666L;

		Object[][] p = {
				{ "阿呆", "Taipei", new Integer(66), new Integer(32),
						new Integer(98), new Boolean(false), new Boolean(false), ""},
				{ "阿瓜", "ChiaYi", new Integer(85), new Integer(69),
						new Integer(154), new Boolean(true), new Boolean(false), "" } };

		String[] n = { "姓名", "居住地", "语文", "数学", "总分", "及格", "作弊", "确认" };

		public int getColumnCount() {
			return n.length;
		}

		public int getRowCount() {
			return p.length;
		}

		public Object getValueAt(int row, int col) {
			return p[row][col];
		}

		// 重写这个方法定义每列的类型
		@Override
		public Class<?> getColumnClass(int c) {
			return getValueAt(0, c).getClass();
		}

		// 重写这个方法定义列名
		@Override
		public String getColumnName(int col) {
			return n[col];
		}

		// 重写这个方法定义单元格是否何以编辑
		@Override
		public boolean isCellEditable(int rowIndex, int columnIndex) {
			return true;
		}

		// 重写这个定义如何给指定单元格赋值
		@Override
		public void setValueAt(Object value, int row, int col) {
			p[row][col] = value;
			fireTableCellUpdated(row, col);
		}
	}

	public static void main(String[] args) {
		new Table_Renderer();
	}
	
	class MyCellRenderer extends JButton
    implements TableCellRenderer {

		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {
			return new JButton("确认");
		}
		
	}

}
